<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\article\controller;
use think\Request;
use mip\Htmlp;
use mip\AdminApiBase;
class ApiAdminArticleCategory extends AdminApiBase
{
    protected $beforeActionList = ['start'];
    public function start() {

    }

    /*
     * 分类模块
     */
    public function do_add()
    {
        $pid = input('post.pid');
        $title = input('post.title');

        $list_preurl =  input('post.list_preurl');
        $detail_preurl =  input('post.detail_preurl');

        if (!$pid) {
            $pid = 0;
        }
        if (!$title) {
            return jsonError('请输入名称');
        }

        // 判断分类名称是否已存在
        $itemCategoryInfo = model('app\article\model\ArticleCategory')->getOne(array('title'=>$title));

        if ($itemCategoryInfo) {
            return jsonError('添加项已存在');
        }

        $arr1 = array(
            'title' => $title,
            'list_preurl' => $list_preurl,
            'detail_preurl' => $detail_preurl,
            'status' => 1,
            'pid' => $pid
        );
        $newId = model('app\article\model\ArticleCategory')->doAddGetId($arr1);
        if ($newId) {

            return jsonSuccess('添加成功');
        } else {
            return  jsonError('添加失败');
        }

    }

    public function do_edit()
    {
        $id = input('post.id');
        $pid = input('post.pid');
        $title = htmlp( input('post.title') );

        $list_preurl =  input('post.list_preurl');
        $detail_preurl =  input('post.detail_preurl');

        $status = input('post.status');

        if (!$id) {
            return jsonError('缺少ID');
        }
        if (!$pid) {
            $pid = 0;
        }
        if (isset($status) && $status == 0) {
            $status = 0;
        } else {
            $status = 1;
        }
        if (!$title) {
            return jsonError('请输入名称');
        }

        $categoryInfo = model('app\article\model\ArticleCategory')->getOne(array('id'=>$id));
        if(!$categoryInfo){
            return jsonError('分类不存在');
        }

        $itemInfo = model('app\article\model\ArticleCategory')->getOne(array('id'=>array('neq',$id ),'title'=>$title));
        if ($itemInfo) {
            return jsonError('标题名已存在，请重新输入');
        }

        $arr1 = array('id' => $id,
            'title' => $title,
            'list_preurl' => $list_preurl,
            'detail_preurl' => $detail_preurl,
            'status' => $status,
            'pid' => $pid
        );
        $dbRes= model('app\article\model\ArticleCategory')->doEdit($id,$arr1);
        if ($dbRes) {
            return  jsonSuccess('修改成功');
        } else if($dbRes === 0){
            return jsonSuccess('您没有调整数据，数据没有变化');
        } else {
            return  jsonError('修改失败 LastSQL -- '.db('articlesCategory')->getLastSql() );
        }
    }

    public function do_sort_save()
    {
        $itemList = input('post.itemList/a');
        if ($itemList) {
            foreach ($itemList as $key => $val) {
                if ($itemListInfo = db('articlesCategory')->where('id',$val['id'])->find()) {
                    $dbRes1= model('app\article\model\ArticleCategory')->doEdit($val['id'],array('sort' => $val['sort']));
                }
                if ($itemList[$key]['children']) {
                    foreach ($itemList[$key]['children'] as $k => $v) {
                        $dbRes2= model('app\article\model\ArticleCategory')->getOne(array('id' => $v['id']));
                        if ($dbRes2) {
                            $dbRes3= model('app\article\model\ArticleCategory')->doEdit($v['id'],array('sort' => $v['sort']));
                        }
                    }
                }
            }
            return jsonSuccess('保存成功');
        }

    }

    public function do_del()
    {
        $id = input('post.id');
        if (!$id) {
            return jsonError('缺少参数4');
        }

        $categoryInfo= model('app\article\model\ArticleCategory')->getById( $id );
        if ($categoryInfo) {
            $itemInfo = db('articles')->where('cid',$categoryInfo['id'])->find();
            if ($itemInfo) {
                return jsonError('删除的项中含有已发布的内容，系统无法删除');
            }
            model('app\article\model\ArticleCategory')->doDelById($id);
            return jsonSuccess('删除成功');
        } else {
            return  jsonError('不存在');
        }

    }

    public function get_list()
    {
        $pid = input('post.pid');
        $limit = input('post.limit');
        $orderBy = input('post.orderBy');
        $order = input('post.order');
        $pid = $pid ? $pid : 0;
        if (!$limit){
            $limit = 1000;
        }
        if (!$orderBy) {
            $orderBy = 'sort';
        }
        if (!$order) {
            $order = 'desc';
        }
        $order = $orderBy.' '.$order;
        $categoryList = model('app\article\model\ArticleCategory')->getListByParent($pid,$order,$limit);
        return jsonSuccess('分类列表获取成功',array('categoryList' => $categoryList) );
    }

    public function get_full_tree(){
        $tree = model('app\article\model\ArticleCategory')->getFullTree();
        return jsonSuccess('获得文章分类树', $tree );
    }

    /**
     * 获取级联选择
     * @return \think\response\Json
     */
    public function get_for_full_cascader ()
    {
        $categoryList = model('ArticleCategory')->getFullCascader();
        return jsonSuccess('获取级联数据成功', $categoryList );
    }

    public function do_move_up(){
        $id= input('post.id');

        $res= model('app\article\model\ArticleCategory')->moveSort($id,'up');
        if($res==1){
            return jsonSuccess('排序已经成功完成。');
        }else if($res==0){
            return jsonSuccess('位置已经是第一个了，无法向前移动');
        }else {
            return jsonError('由于未知原因，排序失败，异常值：'.$res);
        }

    }

    public function do_move_down(){
        $id= input('post.id');

        $res= model('app\article\model\ArticleCategory')->moveSort($id,'down');
        if($res==1){
            return jsonSuccess('排序已经成功完成。');
        }else if($res==0){
            return jsonSuccess('位置已经是最后一个了，无法向后移动');
        }else {
            return jsonError('由于未知原因，排序失败，异常值：'.$res);
        }

    }

    /************************/
    public function moveUp(){
        $id= input('post.id');

        $arrcid = db('articles')
            ->where('id',$id)->field('cid')->find();
        if( !$arrcid ){
            return jsonError('未能获得文章或文章的分类');
        }

        $arts = db('articles')
            ->where('cid',$arrcid['cid'])->field('id')->order('sort asc ')->select();
        if(!$arts){
            return jsonError('未能获得需要排序的文章列表');
        }

        foreach($arts as $k1=>$v1){
            if($k1+1>count($arts)){
                break;
            }

            $tempId = $v1['id'];
            if($k1<count($arts)){
                $nextId = $arts[$k1+1]['id'];
            }
            if($nextId == $id){
                continue;
            }

            // 如果下一个不是 要上移的记录
            if($tempId != $id){
                db('articles')->where('id',$tempId)->update(['sort'=>$k1+1]);
            }else{
                db('articles')->where('id',$tempId)->update(['sort'=>$k1+2]);
                db('articles')->where('id',$nextId)->update(['sort'=>$k1+1]);
            }

        }

        return jsonSuccess('排序已经成功完成。');

    }

    public function moveDown(){
        $id= input('post.id');

        $arrcid = db('articles')
            ->where('id',$id)->field('cid')->find();
        if( !$arrcid ){
            return jsonError('未能获得文章或文章的分类');
        }

        $arts = db('articles')
            ->where('cid',$arrcid['cid'])->field('id')->order('sort asc')->select();
        if(!$arts){
            return jsonError('未能获得需要排序的文章列表');
        }

        foreach($arts as $k1=>$v1){
            if($k1+1>count($arts)){
                break;
            }

            $tempId = $v1['id'];
            if($k1+1<count($arts)){
                $nextId = $arts[$k1+1]['id'];
            }

            if($tempId == $id){
                continue;
            }

            // 如果下一个不是 要上移的记录
            if($nextId != $id){
                db('articles')->where('id',$tempId)->update(['sort'=>$k1+1]);
            }else{
                db('articles')->where('id',$tempId)->update(['sort'=>$k1+2]);
                db('articles')->where('id',$nextId)->update(['sort'=>$k1+1]);
            }

        }

        return jsonSuccess('排序已经成功完成。');

    }

}